package api

import (
	"bytes"
	"compress/gzip"
	"github.com/google/wire"
	"net/http"
	"sieve_admin_server/app/api/util"
	"sieve_admin_server/app/server"
	"sieve_admin_server/app/service"
)

var _ util.API = (*ResourceAPI)(nil)

var ResourceSet = wire.NewSet(wire.Struct(new(ResourceAPI), "*"))

type ResourceAPI struct {
	util.EmptyAPI
	ResourceSrv *service.ResourceSrv
}

func (a *ResourceAPI) GetApis() []*server.BatchModTree {
	return []*server.BatchModTree{
		{
			Obj:   &ResourceAPI{},
			Name:  "businessType",
			Title: "业务类型", Perms: []*server.Perm{
				{Name: "query", Title: "查询"},
				{Name: "add", Title: "新增"},
				{Name: "edit", Title: "修改"},
				{Name: "del", Title: "删除"}},
		},
		{
			Obj:   &ResourceAPI{},
			Name:  "platformVer",
			Title: "平台软件版本", Perms: []*server.Perm{
				{Name: "query", Title: "查询"},
				{Name: "add", Title: "新增"},
				{Name: "edit", Title: "修改"},
				{Name: "del", Title: "删除"}},
		},
	}
}

func (a *ResourceAPI) GetAll(w http.ResponseWriter, r *http.Request) {
	//ss := strings.Split(r.URL.Path[1:], "/")

	uid := server.GetLoginUid(r)
	if uid == 0 {
		w.WriteHeader(http.StatusForbidden)
		w.Write([]byte("not login"))
		return
	}
	//c := &server.Context{Uid: uid, Args: r.PostForm, Http: &server.ContextHttp{ResponseWriter: w, Request: r}}
	//op := ""
	//if len(ss) > 1 {
	//	op = ss[len(ss)-1]
	//}

	data, err := a.ResourceSrv.GetAll(uid)

	if err != nil {
		w.WriteHeader(http.StatusForbidden)
		_, _ = w.Write([]byte(err.Error()))
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Content-Encoding", "gzip")
	buf := new(bytes.Buffer)
	gzw := gzip.NewWriter(buf)
	leng, err := gzw.Write(data.([]byte))
	if err != nil || leng == 0 {
		return
	}
	err = gzw.Flush()
	if err != nil {
		return
	}
	err = gzw.Close()
	if err != nil {
		return
	}
	bt := buf.Bytes()
	_, _ = w.Write(bt)
}
